/**
 * 拖拽相关工具函数
 */
import { tuple, truthy } from '@gnlab/utils'

export function parseWordsId(wordsElement: HTMLElement) {
  const wordsId = parseInt(wordsElement.dataset.wordsId!, 10)
  return isFinite(wordsId) ? wordsId : null
}

export function getWordsElement(element: HTMLElement) {
  let target: HTMLElement | null = element
  while (target) {
    if (truthy(target.dataset.wordsId)) return target
    target = target.parentElement
  }
  return null
}

export function getWordsId(element: HTMLElement) {
  const target = getWordsElement(element)
  return target ? parseWordsId(target) : null
}

export function getAllWordsList(baseElement: HTMLElement) {
  const elements = getWordsElement(baseElement)?.parentElement?.children
  return elements
    ? new Map(
        ([...elements] as HTMLElement[])
          .filter(elm => truthy(elm.dataset.wordsId))
          .map(element => tuple(parseWordsId(element), element))
          .filter((pair): pair is [number, HTMLDivElement] => pair[0] !== null),
      )
    : null
}

/**
 * 把一个数值限定在 min 和 max 之内
 */
export function limit(min: number, value: number, max: number) {
  return Math.max(min, Math.min(max, value))
}
